package com.derbysoft.lowcostadapter.commons.redis.service.impl;

import com.derbysoft.lowcostadapter.commons.model.SystemVariable;
import com.derbysoft.lowcostadapter.commons.redis.service.SystemVariableCacheService;
import com.derbysoft.lowcostadapter.commons.redis.utils.KeyValueHelper;
import com.derbysoft.redis.clients.normal.SingleJedis;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.PipelineBlock;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by: jason
 * Date: 2012-09-25
 */
@Component("systemVariableCacheService")
public class SystemVariableCacheServiceImpl implements SystemVariableCacheService {

    private static Log logger = LogFactory.getLog(SystemVariableCacheServiceImpl.class);

    @Autowired
    private SingleJedis redisCommands;

    @Override
    public SystemVariable load(String key) {
        String value = redisCommands.get(key);
        if (value == null) {
            return null;
        }
        SystemVariable systemVariable = new SystemVariable();
        systemVariable.setName(StringUtils.split(key, KeyValueHelper.SEPARATOR)[1]);
        systemVariable.setValue(StringUtils.trim(value));
        return systemVariable;
    }

    @Override
    public SystemVariable loadByName(String name) {
        return load(SystemVariable.PREFIX + name);
    }

    @Override
    public void saveAll(final List<SystemVariable> systemVariables) {
        final List<SetEntity> setEntities = new ArrayList<SetEntity>();
        for (SystemVariable systemVariable : systemVariables) {
            setEntities.add(SetEntity.build(SystemVariable.PREFIX + systemVariable.getName(), systemVariable.value()));
        }
        try {
            redisCommands.pipelined(new PipelineBlock() {
                @Override
                public void execute() {
                    for (SetEntity setEntity : setEntities) {
                        set(setEntity.getKey(), setEntity.getValue());
                    }
                }
            });
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        }
    }
}
